package org.example.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Classname DemoController
 * @Description TODO
 * @Date 2024/11/15 14:28
 * @author thw
 */
@RestController
public class DemoController {

    @GetMapping("/sayHi")
    @PreAuthorize("hasAnyAuthority('p2')")
    public String sayHi(@RequestParam("name") String name){
        return "sayHi"+name;
    }

    @Autowired
    private ObjectMapper objectMapper;

    @GetMapping("/r1")
    @PreAuthorize("hasAnyAuthority('p1')")
    public String r1(HttpServletRequest httpServletRequest) throws JsonProcessingException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        return objectMapper.writeValueAsString(principal);
    }
}
